<template>
	<view class="detail">
		<unicloud-db #default="{data, loading, error, options}" :collection="collections" :getone="true"
			@load="handleLoad">
			<view v-if="error">{{ error.message }}</view>
			<view v-else-if="loading">
				<u-skeleton rows="25" title loading>
				</u-skeleton>
			</view>
			<view v-else-if="data">
				<view class="contain">
					<view class="title">
						<text>{{ data.title }}</text>
					</view>
					<view class="userinfo">
						<view class="avatar">
							<u-avatar v-if="data.user_id[0]?.avatar_file?.url" :src="data.user_id[0].avatar_file.url"
								size="40"></u-avatar>
							<u-avatar v-else size="40"></u-avatar>
						</view>
						<view style="margin-left: 10rpx;">
							<view class="name">
								<text>{{ data.user_id[0].nickname || data.user_id[0].username }}</text>
							</view>
							<view class="right-btm">
								<view class="time">
									<uni-dateformat :date="data.publish_date"
										format="yyyy年MM月dd日 hh:mm"></uni-dateformat>
								</view>
								<view class="province">
									<text>-发布于{{ data.province }}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="content">
						<u-parse :content="data.content" :selectable="true" :tagStyle="tagstyle"></u-parse>
					</view>
					<view class="like" @click="onclicklike" :class="islike?'active':''" v-if="store.hasLogin">
						<text class="iconfont icon-icon"></text>
					</view>
					<view class="viewer">
						<u-avatar :src="data.user_id[0].avatar_file.url" size="30"></u-avatar>
						<view class="num">
							{{ data.view_count }}<text>人看过</text>
						</view>
					</view>
					<view class="comment">
						<view v-if="!commentlist.length" style="height: 380rpx;">
							<u-empty mode="comment" icon="http://cdn.uviewui.com/uview/empty/comment.png">
							</u-empty>
						</view>
						<view class="content" v-else>
							<view class="item" v-for="item in commentlist" :key="item._id">
								<comment-item :item="item" @delcomment="delComment" @opencomment="openComment"
									:combtn="true"></comment-item>
							</view>
						</view>
					</view>
					<comment-frame :article_id="id" :reply_comment_item="Comment"
						@addcomment="addComment"></comment-frame>
				</view>
			</view>
		</unicloud-db>
	</view>
	<uni-popup ref="popupRef" type="bottom" background-color="#fff" :is-mask-click="false">
		<view class="open-comment" v-if="Comment.item">
			<text class="iconfont icon-guanbi" @click="closeComment"></text>
			<view class="comment-top">
				<comment-item :item="Comment.item" :combtn="false"></comment-item>
			</view>
			<u-divider></u-divider>
			<view class="second-comment">
				<scroll-view scroll-y="true" class="scroll-Y" refresher-enabled="true" :refresher-triggered="refStatus"
					@refresherrefresh="refreshComment" @refresherpulling="refresherpull">
					<view v-for="item in secondcommentlist" :key="item._id" v-if="secondcommentlist.length">
						<comment-item :item="item" :combtn="false" @delcomment="delComment"></comment-item>
					</view>
					<view v-else>
						<u-empty mode="comment" icon="http://cdn.uviewui.com/uview/empty/comment.png">
						</u-empty>
					</view>
				</scroll-view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		getCurrentInstance,
		reactive,
		ref
	} from 'vue'

	import {
		store
	} from '../../uni_modules/uni-id-pages/common/store.js'

	const utilsObj = uniCloud.importObject('utilsobj', {
		customUI: true
	})

	const {
		ctx
	} = getCurrentInstance()

	const islike = ref(false)

	const commentlist = ref([])

	const secondcommentlist = ref([])

	const db = uniCloud.database()

	const tagstyle = {
		p: 'font-size:18px;line-height:1.7em;padding-bottom:10rpx;font-weight:300;',
		img: 'margin: 10px 0'
	}

	const collections = ref([])

	const popupRef = ref()

	const id = ref('')

	const refStatus = ref(false)

	const Comment = reactive({
		item: null
	})

	const onclicklike = async () => {
		let count = await db.collection('blog-like').where(
			`article_id == '${id.value}' && user_id == $cloudEnv_uid`).count()
		if (count.result.total) {
			islike.value = false
			db.collection('blog-like').where(
					`article_id == '${id.value}' && user_id == $cloudEnv_uid`)
				.remove()
			utilsObj.operation('blog', 'like_count', id.value, -1)
			ctx.getOpenerEventChannel().emit('changelike', -1)
		} else {
			islike.value = true
			db.collection('blog-like').add({
				article_id: id.value
			})
			utilsObj.operation('blog', 'like_count', id.value, 1)
			ctx.getOpenerEventChannel().emit('changelike', 1)
		}
	}

	const openComment = (item) => {
		Comment.item = JSON.parse(JSON.stringify(item))
		Comment.item.isShowDel = false
		popupRef.value?.open()
		setTimeout(() => {
			refStatus.value = true
		}, 100)
	}

	const refresherpull = () => {
		refStatus.value = true
	}

	const refreshComment = async () => {
		const info = await uniCloud.getCurrentUserInfo()
		if (Comment.item) {
			const commentTemp = db.collection('blog-news-comments').where(
				`reply_comment_id == '${Comment.item._id}' && article_id == '${id.value}'`).field(
				'article_id,user_id,comment_date,province,comment_content,comment_type,reply_comment_id,reply_user_id'
			).getTemp()
			const userTemp = db.collection('uni-id-users').field('_id,username,nickname,avatar_file').getTemp()
			const res = await db.collection(commentTemp, userTemp).orderBy('comment_date desc').limit(5).get()
			if (res.result) {
				refStatus.value = false
				secondcommentlist.value = res.result.data
				if (Comment.item.user_id === info.uid) {
					secondcommentlist.value.forEach((item) => {
						item.isShowDel = true
					})
				} else {
					secondcommentlist.value.forEach((item) => {
						item.user_id[0]._id === info.uid || info.role[0] == 'admin02' ? item.isShowDel =
							true : item.isShowDel = false
					})
				}
			}
		}
	}

	const closeComment = () => {
		popupRef.value?.close()
		refStatus.value = false
		Comment.item = null
		secondcommentlist.value = []
	}

	const handleLoad = (data) => {
		ctx.getOpenerEventChannel().emit('sonPageData', data)
		if (store.hasLogin && data._id['blog-like'].length) {
			islike.value = true
		}
		uni.setNavigationBarTitle({
			title: data.title
		})
	}

	const getComment = async () => {
		const info = await uniCloud.getCurrentUserInfo()
		const commentTemp = db.collection('blog-news-comments').where(`article_id == '${id.value}' && 
comment_type == 0`).field(
			'article_id,user_id,comment_date,province,comment_content,comment_type').getTemp()
		const userTemp = db.collection('uni-id-users').field('_id,username,nickname,avatar_file').getTemp()
		const res = await db.collection(commentTemp, userTemp).orderBy('comment_date desc').limit(5).get()
		commentlist.value = res.result.data
		commentlist.value.forEach((item) => {
			db.collection('blog-news-comments').where(`reply_comment_id == '${item._id}'`).count().then(
				data => {
					item.reply_count = data.result.total
				})
			item.user_id[0]._id === info.uid || info.role[0] == 'admin02' ? item.isShowDel = true : item
				.isShowDel = false
		})
	}

	const addComment = async (item) => {
		if (item) {
			const res = await db.collection('uni-id-users').where('_id == $cloudEnv_uid').field(
				'_id,username,nickname,avatar_file').get()
			const newComment = {
				user_id: [res.result.data[0]],
				...item,
				isShowDel: true
			}
			ctx.getOpenerEventChannel().emit('changecomment', 1)
			if (!newComment.comment_type) {
				newComment.reply_count = 0
				commentlist.value.unshift(newComment)
				commentlist.value = commentlist.value.slice(0, 5);
			} else {
				commentlist.value.forEach((comment) => {
					if (comment._id === item.reply_comment_id) {
						comment.reply_count++
					}
				})
				secondcommentlist.value.unshift(newComment)
				secondcommentlist.value = secondcommentlist.value.slice(0, 5)
			}
		}
	}

	const delComment = (comment) => {
		if (comment.comment_type) {
			commentlist.value.forEach((item) => {
				if (item._id === comment.reply_comment_id) {
					item.reply_count--
				}
			})
			const index = secondcommentlist.value.findIndex((item) => item._id === comment._id)
			secondcommentlist.value.splice(index, 1);
			ctx.getOpenerEventChannel().emit('changecomment', -1)
		} else {
			const index = commentlist.value.findIndex((item) => item._id === comment.item._id)
			commentlist.value.splice(index, 1);
			ctx.getOpenerEventChannel().emit('changecomment', -comment.num)
		}
	}

	onLoad((e) => {
		if (!e.id) {
			uni.showToast({
				title: '参数有误',
				icon: 'none'
			})
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}, 1000)
			return;
		}
		id.value = e.id
		utilsObj.operation('blog', 'view_count', e.id, 1)
		collections.value = [
			db.collection('blog').where(`_id == '${e.id}'`).getTemp(),
			db.collection('uni-id-users').field('_id,username,nickname,avatar_file').getTemp()
		]
		if (store.hasLogin) {
			collections.value.push(db.collection('blog-like').where(
				`article_id == '${e.id}' && user_id == $cloudEnv_uid`).getTemp())
		}
		getComment()
	})
</script>

<style scoped lang="scss">
	::v-deep .uni-easyinput__content-input {
		height: 80rpx !important;
	}

	::v-deep .uniui-paperplane-filled {
		font-size: 30px !important;
		color: #2ac2d1 !important;
	}

	.detail {
		background-color: #f8f8f8;
		min-height: calc(100vh - var(--window-top));

		.contain {
			padding: 30rpx;
			background-color: #fff;

			.title {
				font-size: 46rpx;
				color: #333;
				font-weight: 600;
				line-height: 1.4em;
			}

			.userinfo {
				height: 120rpx;
				width: 100%;
				display: flex;
				align-items: center;
				color: #999;

				.name {
					font-size: 35rpx;
				}

				.avatar {
					margin: 10rpx;
				}

				.right-btm {
					margin-top: 10rpx;
					display: flex;
					font-size: 25rpx
				}
			}

			.like {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				width: 180rpx;
				height: 100rpx;
				background-color: #e4e4e4;
				border-radius: 50rpx;
				margin: 30rpx auto;
				color: #000;

				.iconfont {
					font-size: 45rpx;
				}

				.like_count {
					font-size: 20rpx;
				}

				&.active {
					color: #2ac2d1;
				}
			}

			.viewer {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.num {
					margin-top: 10rpx;
					font-size: 20rpx;
					color: #2ac2d1;

					text {
						color: #333;
					}
				}
			}

			.comment {
				padding: 10rpx;
				padding-bottom: 90rpx;

				.content {
					margin-top: 20rpx;
				}
			}
		}
	}

	.open-comment {
		padding: 10rpx 20rpx;

		.iconfont {
			float: right;
			font-size: 35rpx;
			margin: 5rpx 0;
		}

		.comment-top {
			padding-top: 60rpx;
		}

		.second-comment {
			height: 600rpx;
			width: 100%;
			background-color: #f8f8f8;
			border-radius: 20rpx;
			margin-bottom: 60rpx;

			.scroll-Y {
				height: 600rpx;
			}
		}
	}
</style>